<?php
abstract class UploadWidget extends CWidget implements IBehavior {
    const  PREFIX = 'upl.';           // Prefix for controllers

    // Parameters
    public static $tempDir = 'tmp';   // Temporal dir for storing files if necessary
    public static $fileDir = 'files'; // Definitive repository dir for storing files

    public $model; // Model with files attached

    public function init() {
        // Ensure the model is attached
        if ($this->model != null) $this->attach($this->model);
    }

    public function renderPartial($view, $params) {
        $view = $this->getViewFile($view);
        $this->renderFile($view, $params);
    }

    ///////////////////////////////// IBehavior implementation (from CBehaviour)
    private $_enabled;
    private $_owner;

	public function events() { return array(); }
   
    /**
     * Attaches the behavior object to the component.
     * The default implementation will set the {@link owner} property
     * and attach event handlers as declared in {@link events}.
     * Make sure you call the parent implementation if you override this method.
     * @param CComponent the component that this behavior is to be attached to.
     */
    public function attach($owner) {
        $this->_owner=$owner;
        foreach($this->events() as $event=>$handler)
            $owner->attachEventHandler($event,array($this,$handler));

        // Attach relation to the model
        $owner->metadata->relations['files'] = new CHasManyRelation(
                'files', 'File', 'EXid',
                array(
                    'condition'=>"entity='".get_class($owner)."'",
                    'order'=>'weight ASC',
                ));
    }
    /**
     * Detaches the behavior object from the component.
     * The default implementation will unset the {@link owner} property
     * and detach event handlers declared in {@link events}.
     * Make sure you call the parent implementation if you override this method.
     * @param CComponent the component that this behavior is to be detached from.
     */
    public function detach($owner) {
        foreach($this->events() as $event=>$handler)
            $owner->detachEventHandler($event,array($this,$handler));
        $this->_owner=null;

        // Dettach relation of the model
        unset($owner->metadata->relations['files']);
    }
    /** @return CComponent the owner component that this behavior is attached to. */
    public function getOwner() { return $this->_owner; }
    /** @return boolean whether this behavior is enabled */
    public function getEnabled() { return $this->_enabled; }
    /** @param boolean whether this behavior is enabled */
    public function setEnabled($value) {  $this->_enabled=$value; }

}